package com.supermap.business.user;

import com.alibaba.dubbo.config.annotation.Reference;
import com.supermap.dataservice.util.JSONUtil;
import com.supermap.dataservice.util.JSONUtils;
import com.supermap.dataservice.util.MD5Util;
import com.supermap.dataservice.util.Table;
import com.supermap.dubbo.api.agrinfo.entity.Agrinfo;
import com.supermap.dubbo.api.iot.IotUserBindService;
import com.supermap.dubbo.api.user.UserService;
import com.supermap.dubbo.api.user.entity.BindUser;
import com.supermap.dubbo.api.user.entity.InterNetInfo;
import com.supermap.dubbo.api.user.entity.User;
import com.supermap.dubbo.api.user.entity.Vip;
import com.supermap.shiro.auth.entity.AppUser;
import com.supermap.shiro.common.AuthFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.supermap.dataservice.util.Export.ExportResponse;

/**
 * @Author:langhongshuai
 * @Description:用户接口层
 * @Date:18/1/3 下午4:08
 */
@Controller
@RequestMapping("UserController")
public class UserController {
    /**
     * 使用指定类初始化日志对象，在日志输出的时候，可以打印出日志信息所在类
     */
    protected static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Reference(timeout = 1000000)
    private UserService userService;

    private MD5Util md5Util = new MD5Util();

    /**
     * 通过Id查询用户
     */
    @PostMapping("/updateUserlatlongByUserId")
    @ResponseBody
    public JSONUtil updateUserlatlongByUserId(String UserId, BigDecimal longitude, BigDecimal  latitude) {
        return userService.updateUserlatlongByUserId(UserId,longitude,latitude);
    }

    /**
     * 合法性Check
     */
    @RequestMapping("checkUser")
    public void checkUser() {

    }

    /**
     * 头像上传
     */
    @RequestMapping("headImgUpLoad")
    public void headImgUpload() {

    }

    /**
     * 密码重置
     *
     * @param request
     */
    @RequestMapping("resetPassword")
    @ResponseBody
    public JSONUtil resetPassword(HttpServletRequest request) {
        //获取用户名、旧密码以及新密码
        String userName = request.getParameter("userName");
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        if ((userName == null && oldPassword == null && newPassword == null) || (userName.isEmpty() && oldPassword.isEmpty() && newPassword.isEmpty())) {
            JSONUtil jsonUtil = new JSONUtil();
            logger.info("userController=>resetPassword=>AllParameter=>null");
            jsonUtil.setMsg("Reset password failed！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
            return jsonUtil;
        }
        return userService.resetPassword(userName, oldPassword, newPassword);

    }

    /**
     * 通过Id查询用户
     */
    @RequestMapping("queryUserById")
    public void queryUser() {

    }

    /**
     * 根据用户名获取用户信息
     *
     * @param request
     * @return
     */
    public JSONUtil queryUserByUsername(HttpServletRequest request) {
        String username = request.getParameter("loginName");
        return null;
    }

    /**
     * 增加用户
     */
    @RequestMapping("insertUser")
    public void insertUser(HttpServletRequest request) {
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");
        String mobile = request.getParameter("mobile");
        String areaCode = request.getParameter("areaCode");
        String realName = request.getParameter("realName");
        String latitude = request.getParameter("latitude");
        String longitude = request.getParameter("longitude");
        User user = new User();
        user.setLoginName(loginName);
        user.setUsername(realName);
        user.setPassword(password);
        user.setAreaCode(areaCode);
        user.setMobile(mobile);
        user.setLatitude(latitude);
        user.setLongitude(longitude);
        userService.insertUser(user);
    }

    /**
     * 通过角色id和区域获取用户信息
     */
    @RequestMapping("findUserByAreaRId")
    @ResponseBody
    public JSONUtil findUserByAreaRId(HttpServletRequest request) {
        String areaCode = request.getParameter("areaCode");
        String roleId = request.getParameter("roleId");
        return userService.findUserByAreaRId(areaCode, Integer.valueOf(roleId));
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/updateUserById")
    @ResponseBody
    public JSONUtil updateUserById(User user) {
        return userService.updateUserById(user);
    }

    /**
     * 修改用户信息
     *
     * @param user)
     * @return
     */
    @RequestMapping(value = "/updateUser")
    @ResponseBody
    public JSONUtil updateUser(@RequestBody User user) {
        AppUser appUser = AuthFactory.getLoginUser(false);
        if (appUser == null) {
            return userService.updateUser(user);
        }
        User tmp = appUser.assistToUser();
        tmp.updateUser(user);
        AuthFactory.updateUser(tmp);
        return userService.updateUser(tmp);
    }

    /**
     * 通过area获取ip地址
     *
     * @param areaCode
     * @return
     */
    @RequestMapping(value = "/getURLByAreaCode")
    @ResponseBody
    public JSONUtil getURLByAreaCode(String areaCode) {
        return userService.getURLByAreaCode(areaCode);
    }

    /***
     * sms获取用户信息
     * ***/
    @RequestMapping("/getSmsUserList")
    @ResponseBody
    public Table getSmsUserList(Table table, User user) {

        JSONUtil jsonUtil = userService.getUserList(table, user);
        table = (Table) jsonUtil.getData();
        table.setMsg(jsonUtil.getMsg());
        table.setCode(jsonUtil.getCode());
        return table;
    }

    /****
     * 导出用户数据
     * ***/
    @RequestMapping(value = "/userListExcel")
    public void agriExcel(HttpServletRequest request, HttpServletResponse response, Table table, User user) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "1800");
        String sheetName = "用户信息";
        String titleName = "用户信息";
        String fileName = "用户信息";
        int columnNumber = 9;
        int[] columnWidth = {10, 20, 20, 20,30, 20, 40, 20,20};
        List<User> list =userService.usersExcel(table, user);
        //st转二维数组
        String[] columnName = {"用户名", "账号", "真实姓名", "电话号码","角色","地址","区域","邮箱","状态"};
        String[][] dataList = new String[list.size()][columnName.length];
        for (int i = 0; i < list.size(); i++) {
            User u = list.get(i);
            dataList[i][0]=u.getUsername();
            dataList[i][1]=u.getLoginName();
            dataList[i][2]=u.getShowName();
            dataList[i][3]=u.getMobile();
            dataList[i][4]=u.getRolename();
            dataList[i][5]=u.getAddress();
            dataList[i][6]=u.getAreaname();
            dataList[i][7]=u.getEmail();
            dataList[i][8]=u.getState();
        }

        ExportResponse(sheetName, titleName, fileName,
                columnNumber, columnWidth, columnName, dataList, response);
    }

    /**
     * app获取用户列表
     *
     * @param table user
     * @return
     */
    @RequestMapping(value = "/getUserList")
    @ResponseBody
    public Table getUserList(Table table, User user) {
        JSONUtil jsonUtil = userService.getAppUserList(table, user);
        table = (Table) jsonUtil.getData();
        table.setMsg(jsonUtil.getMsg());
        table.setCode(jsonUtil.getCode());
        return table;
    }

    /**
     * 模糊查询用户列表
     *
     * @param keyWord 模糊查询关键字
     * @return
     */
    @RequestMapping(value = "/getUserInfoByUserNameLike")
    @ResponseBody
    public JSONUtil getUserInfoByUserNameLike( String showName,String areaCode,String pageNum,String pageSize) {
        if (showName == null) {
            JSONUtil jsonUtil = new JSONUtil();
            jsonUtil.setMsg("Get users flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
            return jsonUtil;
        }

        return userService.searchUserInfoByKeyWord(showName, (Integer.valueOf(pageNum)-1)*Integer.valueOf(pageSize), Integer.valueOf(pageSize),areaCode);
    }

    /**
     * 模糊查询用户列表
     *
     * @param showName
     * @param type
     * @param areaCode
     * @return
     */
    @RequestMapping(value = "/searchVip")
    @ResponseBody
    public JSONUtil searchVip(@RequestParam("showName") String showName, @RequestParam("type") String type, @RequestParam("areaCode") String areaCode) {
        if (showName == null) {
            JSONUtil jsonUtil = new JSONUtil();
            jsonUtil.setMsg("search Vip flase！");
            jsonUtil.setIsSuccess(false);
            jsonUtil.setCode(100);
            return jsonUtil;
        }
        int page = 0;
        int count = 1000;
        return userService.searchVip(showName, type, areaCode, page, count);
    }

    /**
     * 通过id删除用户
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "delUserById")
    @ResponseBody
    public JSONUtil delUserById(int userId) {
        return userService.delUserById(userId);
    }


    /**
     * 申请成VIP
     *
     * @param vip 用户ID
     * @return
     */
    @RequestMapping(value = "applyForVIP")
    @ResponseBody
    public JSONUtil applyForVIP(Vip vip) {
        return userService.applyForVIP(vip);
    }


    /**
     * 申请成VIP
     *
     * @param userId 用户ID
     * @return
     */
    @RequestMapping(value = "affirmToVIP")
    @ResponseBody
    public JSONUtil affirmToVIP(String userId) {
        return userService.affirmToVIP(userId);
    }

    /**
     * 增加用户
     */
    @RequestMapping("insertUserCQ")
    @ResponseBody
    public JSONUtil insertUserCQ(InterNetInfo us) {
        us.setCreatetime(new Timestamp(new Date().getTime()));
        try {
            us.setPassword(md5Util.EncoderByMd5(us.getPassword()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return userService.insertUserCQ(us);
    }

    /***
     * 区域信息
     * **/
    @RequestMapping(value = "/getArea")
    @ResponseBody
    public JSONUtil getArea() {

        JSONUtil jsonUtil = new JSONUtil();
        jsonUtil.setCode(200);
        jsonUtil.setMsg("success");
        jsonUtil.setIsSuccess(true);
        jsonUtil.setData(userService.getAreaInfo());
        return jsonUtil;
    }

    /***
     * 全国省,市，县信息
     * **/
    @RequestMapping(value = "/getProvince")
    @ResponseBody
    public JSONUtil getProvince() {

        JSONUtil jsonUtil = new JSONUtil();
//        if(type==1){
            jsonUtil.setCode(200);
            jsonUtil.setMsg("success");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setData(userService.getProvince());
//        }else if(type==2){
//            jsonUtil.setCode(200);
//            jsonUtil.setMsg("success");
//            jsonUtil.setIsSuccess(true);
//            jsonUtil.setData(userService.getCity(areaCode,"市"));
//        }else{
//            jsonUtil.setCode(200);
//            jsonUtil.setMsg("success");
//            jsonUtil.setIsSuccess(true);
//            jsonUtil.setData(userService.getCounty(areaCode,""));
//        }

        return jsonUtil;
    }

    /***
     * 获取角色信息
     * **/
    @RequestMapping(value = "/getRole")
    @ResponseBody
    public JSONUtil getRole() {

        JSONUtil jsonUtil = new JSONUtil();
        jsonUtil.setCode(200);
        jsonUtil.setMsg("success");
        jsonUtil.setIsSuccess(true);
        jsonUtil.setData(userService.getRole());
        return jsonUtil;
    }

    /**
     * 密码重置
     *
     * @param request
     */
    @RequestMapping("resetPasswordCQ")
    @ResponseBody
    public JSONUtil resetPasswordCQ(HttpServletRequest request, int userId) {
        //获取用户名、旧密码以及新密码

        if (request.getParameter("newPassword") != null && !"".equals(request.getParameter("newPassword"))) {
            String newPassword = request.getParameter("newPassword");

            return userService.resetPasswordCQ(userId, newPassword);
        }
        JSONUtil jsonUtil = new JSONUtil();
        logger.info("userController=>resetPassword=>AllParameter=>null");
        jsonUtil.setMsg("Reset password failed！");
        jsonUtil.setIsSuccess(false);
        jsonUtil.setCode(100);
        return jsonUtil;

    }

    /**
     * 通过id删除用户
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "updateStatus")
    @ResponseBody
    public JSONUtil updateStatus(int userId) {
        return userService.updateStatus(userId);
    }
    @Reference
    private IotUserBindService iotUserBindService;
    //物联网账户
    public  AppUser setAppUser(AppUser user){
        try{
            List<Map<String,Object>> listMap=(List<Map<String,Object>>)iotUserBindService
                    .getBindUserId(user.getId()).getData();
            user.setLoginIotName(listMap.get(0).get("w_loginName").toString());
            user.setLoginIotPassword(listMap.get(0).get("w_password").toString());
        }catch (Exception e){
            return  user;
        }
        return  user;
    }
    /***
     * 查询用户是否存在
     * ***/
    @RequestMapping("/queryBindUser")
    @ResponseBody
    public JSONUtil queryBindUser() {
        JSONUtil jsonUtil = new JSONUtil();
        AppUser appUser = AuthFactory.getLoginUser(true);
        if(appUser!=null){
            appUser=setAppUser(appUser);
        }
        //通过session获取appUserId
        if (appUser != null) {
            //判断用户是否存在，并返回用户信息
            if (appUser.getLoginIotName() != null &&!appUser.getLoginIotName().equals("")) {
                //更新session
                AuthFactory.putBindUser(appUser.getLoginIotName(),appUser.getLoginIotPassword());
                //session更新，把物联网的用户名密码存到session
                jsonUtil.setMsg("获取成功！");
                jsonUtil.setCode(200);
                jsonUtil.setIsSuccess(true);
            } else {
                jsonUtil.setMsg("获取失败！请先绑定用户！");
                jsonUtil.setCode(20000);
                jsonUtil.setIsSuccess(true);
            }

        } else {
            jsonUtil.setMsg("获取失败！请先登陆");
            jsonUtil.setCode(10000);
            jsonUtil.setIsSuccess(true);
        }
        //返回结果
        return jsonUtil;
    }

    /***
     * 插入绑定用户
     * ***/
    @RequestMapping("/insertBindUser")
    @ResponseBody
    public JSONUtil insertBindUser(@RequestBody BindUser bindUser) {
        JSONUtil jsonUtil = new JSONUtil();
        AppUser appUser = AuthFactory.getLoginUser(true);

        if (appUser == null) {
            //返回未登录
            jsonUtil.setMsg("请先登录！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(10000);
            return jsonUtil;
        }
        //
        BindUser user = appUser.assistToBindUser();
        user.updateBindUser(bindUser);
        //存session
        AuthFactory.updateBindUser(bindUser);
        return userService.insertBindUser(user.getUserId(), user.getLoginName(), user.getPassword());
    }
/***
 * 插入企业员工
 * ***/
    @RequestMapping("/insertVipUser")
    @ResponseBody
    public JSONUtil insertVipUser(User user) {
        JSONUtil jsonUtil = new JSONUtil();
        AppUser appUser = AuthFactory.getLoginUser(false);
        if (appUser == null) {
            jsonUtil.setMsg("用户未登陆！");
            jsonUtil.setIsSuccess(true);
            jsonUtil.setCode(300);
            return jsonUtil;
        }
        user.setCreatetime(new Timestamp(new Date().getTime()));
        try {
            user.setPassword(md5Util.EncoderByMd5(user.getPassword()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return userService.addVipUser(user, Integer.parseInt(appUser.getId()));
    }
    /***
     *获取企业员工
     * ***/
    @RequestMapping("/getVipUserList")
    @ResponseBody
    public Table getVipUserList(Table table, User user) {

        AppUser appUser = AuthFactory.getLoginUser(false);
        JSONUtil jsonUtil = new JSONUtil();
        if (appUser == null) {
            table.setMsg("用户未登陆！");
            table.setCode(300);
        }

        jsonUtil = userService.queryVipUserList(table, user, Integer.parseInt(appUser.getId()));
        table = (Table) jsonUtil.getData();
        table.setMsg(jsonUtil.getMsg());
        table.setCode(jsonUtil.getCode());
        return table;
    }

    /****
     * 跟新用户状态
     * ***/
    @RequestMapping("/updateState")
    @ResponseBody
    public JSONUtil updateState(String state,int id){

        return  userService.updateState(state,id);
    }

    /**
     * 根据乡镇编码查找用户信息
     * @param townCodes
     * @return
     */
    @RequestMapping("/queryUserByTownCode")
    @ResponseBody
    public JSONUtils queryUserByTownCode(String townCodes)
    {
        return  userService.queryUserByTownCode(townCodes);
    }

    /**
     * 根据农田的乡镇编码查找用户
     * @param cropCode
     * @param townCodes
     * @return
     */
    @RequestMapping("/queryUserByFaramTownCode")
    @ResponseBody
    public JSONUtils queryUserByFaramTownCode(String cropCode , String townCodes)
    {
        return  userService.queryUserByFaramTownCode(cropCode ,townCodes);
    }

}



